package com.ruoyi.system.service.impl;

import com.ruoyi.system.service.EcService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

/**
 * @Description:
 * @Author:let_free
 * @Date:2024/11/18/13:45
 **/
@Service
public class EcServiceImpl implements EcService {
    Logger logger = Logger.getLogger(EcServiceImpl.class.getName());

    //EC预报降雨存储路径
    @Value("${ec}")
    private String ECPath;

    @Override
    public Map<String, String> getDefaultImage(String type, String queryTime) {
        File file = new File(ECPath, type);
        if (queryTime == null) {
            return getFirstImageNameFromDirectory(file.getAbsolutePath());
        } else {
            return getImageByName(file.getAbsolutePath(), queryTime);
        }
    }

    private Map<String, String> getFirstImageNameFromDirectory(String directoryPath) {
        Map<String, String> result = new HashMap<>();
        File directory = new File(directoryPath);
        if (!directory.exists() || !directory.isDirectory()) {
            return null;
        }
        result.put("path", directoryPath);
        File[] files = directory.listFiles();
        Arrays.sort(files, Comparator.comparing(File::getName).reversed());
        if (files != null && files.length > 0) {
            String fileName = files[0].getName();
//            图片名称 时间戳（小时） 和未来预测间隔
            result.put("name", fileName);
            result.put("timeStamp", fileName.substring(0, 10));
            result.put("predictionGap", fileName.substring(10, 12));
            return result;
        }
        return null;
    }

    /**
     * @param directoryPath /opt/homebrew/etc/nginx/Save/ec/ecrain
     * @param queryTime     ECRAIN202307312012.png
     * @return java.util.Map<java.lang.String, java.lang.String>
     * @description
     * @author let_free
     * @date 2024/11/18 16:49
     */

    private Map<String, String> getImageByName(String directoryPath, String queryTime) {
        File file = new File(directoryPath, queryTime);
//        查询的文件不存在
        if (!file.exists()) {
            logger.info("文件不存在");
            return null;
        }
        Map<String, String> result = new HashMap<>();
        result.put("path", directoryPath);
        result.put("name", queryTime);
        result.put("timeStamp", queryTime.substring(0, 10));
        result.put("predictionGap", queryTime.substring(10, 12));
        return result;
    }
}
